<?php

require_once 'projekt_st\spletne\entity\Oseba.php';
require_once 'projekt_st\spletne\entity\Aktivnosti.php';
require_once 'projekt_st\spletne\entity\Izobrazba.php';
require_once 'projekt_st\spletne\entity\DelovneIzkusnje.php';
require_once 'projekt_st\spletne\entity\Povezave.php';
require_once 'projekt_st\spletne\entity\Znanja.php';
require_once 'projekt_st/spletne/entity/Profesor.php';
require_once 'projekt_st/spletne/entity/PrijavniPodatki.php';
require_once 'projekt_st/spletne/entity/Jeziki.php';
require_once 'projekt_st/spletne/entity/Mapa.php';
require_once 'projekt_st/spletne/entity/Datoteke.php';

class PB {
    
	
	private $db_host  = 'localhost';
	private $db_name= 'spletnetehnologije';
	private $db_username = 'root';
	private $db_password = '';
	private $db_conn;
	private $result;
	
    //prijava na bazo
    public function conn() {
    	
    	try {
    		$db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", 
        					$this->db_username, $this->db_password);
    	} catch (PDOException $e) {
    		echo 'could not connect to Database! Message: '.$e;
    	}
        
        	$this->db_conn = $db_conn;
        	//return $db_conn;	     				
    }
    
    
    public function disconnect(){
    	if($this->db_conn){
    		$this->db_conn = null;
    	}
    }
     
    public function read($table, $rows='*', $where = null, $order = null, $multiple = false){
    	    	
    	//print_r($where);
    	
     	$sql = "SELECT * FROM $table "; 
    	if($where != null){
    		$sql .= "WHERE ";
     		$keys = array_keys($where);
     		//print_r($keys[0]);
     		
     		for($i=0; $i<count($keys); $i++){
     			//ce je string ga ovijemo v narekovaje
     			if(is_string($where[$keys[$i]])){
     				$sql .= $keys[$i]. " = " . "'".$where[$keys[$i]]."'";
     			}else{
     				$sql .= $keys[$i]. " = " . $where[$keys[$i]];
     			}
     			
     			if($i < (count($keys)-1)){
     				$sql .= " AND ";
     			}   			
     		}
     	
     	}
     	if($order != null) {
            $sql .= ' ORDER BY '.$order;  
     	}
    	//echo "pripravljen SQL v bazi: ".$sql. "<br>";
     	
        if($this->tableExists($table))  
        {          	 
        	$stmt = $this->db_conn->prepare($sql);
        	//print_r($stmt);
        	$stmt->execute();
        	if($multiple){
        		$result = $stmt->fetchAll(PDO::FETCH_CLASS,$table);
        	}else{
        		$result = $stmt->fetchObject($table);
        	}
        	
        	//echo "<br>SEM V PB fetchobject()... <br>";
        	//print_r($result);
	        return $result;
        }  
		else  
			//echo 'sem v false!';
      		return false; 
	 
    }
    
    
    public function write($table,$values=null,$object=null) {
    	if($this->tableExists($table)){
//    		$sql = "INSERT INTO ".$table." (";
//    		$keys = array_keys($values);
//    		$stringKeys = implode(',',$keys);
			if($object != null){
				$attrArray = $object->getClassAttributes();
				$sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")',$table,implode(", ",array_keys($attrArray)),implode('", "',$attrArray));
			}else{
				$sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")', $table, implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));
			}
    		
    		//
    		
    		//echo $sql;
    		
    		$stmt = $this->db_conn->prepare($sql);
    		$stmt->execute();
    		//$result = $stmt->rowCount();
   			//echo "<br>Affected rows: " . $result;
    		
    		return $this->db_conn->lastInsertId();
    	}else{
    		return false;
    	}
    	
    }
    
    
    public function update($table,$values,$where) {
    	if($this->tableExists($table)){
    		
    		$sql = "UPDATE $table SET ";
    		$keys = array_keys($values);
    		
    		for($i=0; $i<count($keys); $i++){
     			//ce je string ga ovijemo v narekovaje
     			if(is_string($values[$keys[$i]])){
     				$sql .= $keys[$i]. " = " . "'".$values[$keys[$i]]."'";
     			}else{
     				$sql .= $keys[$i]. " = " . $values[$keys[$i]];
     			}
     			
     			if($i < (count($keys)-1)){
     				$sql .= " , ";
     			}   			
     		}
    		
    		
    		$sql .= " WHERE ";
    		
    		$keys = array_keys($where);
     		//print_r($keys[0]);
     		
     		for($i=0; $i<count($keys); $i++){
     			//ce je string ga ovijemo v narekovaje
     			if(is_string($where[$keys[$i]])){
     				$sql .= $keys[$i]. " = " . "'".$where[$keys[$i]]."'";
     			}else{
     				$sql .= $keys[$i]. " = " . $where[$keys[$i]];
     			}
     			
     			if($i < (count($keys)-1)){
     				$sql .= " AND ";
     			}   			
     		}
    	}
    	//echo $sql." <br>";
    	
    	$stmt = $this->db_conn->prepare($sql);
    	$stmt->execute();
    	$result = $stmt->rowCount();
    	//echo $result;
    	//echo "rows affected: ".$result;
    	return $result;
    }
    
    
    public function delete($table,$id=null) {
    	
    	$table = mysql_escape_string($table);
    	
    	if($this->tableExists($table))  
        {  
            if($id == null){  
                $sql = 'DELETE FROM '.$table;  
            }  
            else{  
                $sql = 'DELETE FROM '.$table." WHERE id$table=".mysql_escape_string($id);
                  
            }  
            //echo $sql."<br>";
            $rowsAffected = $this->db_conn->exec($sql);
            
  
            return $rowsAffected;
        }  
        else  
        {  
            return false;  
        } 
    	
    }
    
     
	private function tableExists($table)  
    {  
    	$sql = "SHOW TABLES FROM spletnetehnologije LIKE '$table'";
        //$tablesInDb = @mysql_query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$table.'"'); 
        //echo "table exists SQL: ". $sql; 
        $stmt = $this->db_conn->query($sql);
      
        $row = $stmt->fetch();
        
        if(!empty($row)){
        	//echo "<br>tabela obstaja<br>";
        	return true;
        }else{
        	//echo "tabela $table ne obstaja";
        	return false;
        }
    	
    	
    	return true;
    }
    
    public function getConnection(){
    	return $this->db_conn;
    }
    
    public function getResult(){
    	return $this->result;
    }
     
    
    
    
    public function login($username,$password) {
 		//prijavni podatki
 		
    	$podatki = array();
 		$this->conn();
    	$sql = "SELECT * FROM prijavnipodatki WHERE upIme= :username AND geslo= :password";
    	$stmt = $this->db_conn->prepare($sql);
    	$stmt->bindValue(":username", mysql_real_escape_string($username));
    	$stmt->bindValue(":password",md5(mysql_real_escape_string($password)));
    	$stmt->execute();
    	$result = $stmt->fetch(PDO::FETCH_ASSOC);
    	
    	$podatki["tipUporabnika"] = $result["tip"];
    	//vrne osebo za sejo, ce oseba registrirana
    	if($result != null){
    		//$oseba = $this->read('oseba','*',array("prijavniPodatki_idprijavniPodatki" => $result["idprijavniPodatki"]),null,false);
	    	if($podatki["tipUporabnika"] == "student"){
	    		$sql = "SELECT * FROM oseba WHERE prijavniPodatki_idprijavniPodatki = :id";
	    	}else if($podatki["tipUporabnika"] == "profesor"){
	    		$sql = "SELECT * FROM profesor WHERE prijavniPodatki_idprijavniPodatki = :id";
	    	}
    		
    		$stmt = $this->db_conn->prepare($sql);
    		$stmt->bindValue(":id", $result["idprijavniPodatki"]);
    		$stmt->execute();
    		$oseba = $stmt->fetch(PDO::FETCH_ASSOC);
    		//echo "V BAZI za login: <br>";
	    	//print_r($oseba);
	    	$podatki["uporabnik"] = $oseba;
	    	$podatki["uporabnik"]["upIme"] = $result["upIme"];
	    	return $podatki;
    	}else{
    		return false;
    	}
    	
    	
    	
    	
    }
    
    
	public function array_slice_assoc ($array, $key, $length, $preserve_keys = true)
	{
	   $offset = array_search($key, array_keys($array));
	
	   if (is_string($length))
	      $length = array_search($length, array_keys($array)) - $offset;
	
	   return array_slice($array, $offset, $length, $preserve_keys);
	}
	
	
	public function search($table,$string) {
		$string = "'%".$string."%'";
		$string = htmlentities($string);
		
		
		$sql = "SELECT * FROM $table WHERE ime LIKE $string OR priimek LIKE $string"; 
    	
		//echo "SEM V BAZI: ".$sql. " STRING: ". $string;
     	$stmt = $this->db_conn->prepare($sql);
     	//$stmt->bindValue(":ime", $string,PDO::PARAM_STR);
     	//$stmt->bindValue(":priimek", $string);
     	
     	$stmt->execute();
     	
     	$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
     	     		
     
     	//echo "<br>REZULTAT: <br>";
     	//print_r($result);
 		return $result;
	}
 }

?>